package com.rapida.theme;

import java.util.ArrayList;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;

import com.rapida.app.BaseActivity;
import com.rapida.theme.ThemeManager.OnThemeChangedListener;

public class ThemeActivity extends BaseActivity implements OnThemeChangedListener {
	private ThemeManager mThemeManager;
	private ThemeResources mRes;
	private SharedPreferences mPreferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mRes = new ThemeResources(getResources());
		mThemeManager = ThemeManager.get(getBaseContext());
		mThemeManager.searchTheme();
		mThemeManager.setOnThemeChangedListener(this);
		mPreferences = getSharedPreferences("ThemePlugin", Context.MODE_PRIVATE);
		setThemeContext(getThemePackageName());
	}

	public String getThemePackageName() {
		return mPreferences.getString("themePackageName", null);
	}

	public ArrayList<String> getThemes() {
		return mThemeManager.getThemes();
	}

	public ThemeResources getThemeResources() {
		return mRes;
	}

	private boolean setThemeContext(String newThemePackageName) {
		if (newThemePackageName == null) {
			return false;
		}
		try {
			Context themeContext = createPackageContext(newThemePackageName, CONTEXT_IGNORE_SECURITY);
			mRes.setThemeContext(themeContext);
		} catch (NameNotFoundException e) {
			return false;
		}
		return true;
	}
	
	public void applyTheme(String newThemePackageName) {
		if (setThemeContext(newThemePackageName)) {
			mThemeManager.applyTheme(newThemePackageName);
		}
	}

	@Override
	public void OnThemeChanged(String newThemePackageName) {
		Editor edit = mPreferences.edit();
		edit.putString("themePackageName", newThemePackageName);
		edit.commit();
	}

}
